import { Http } from '@angular/http';
import { Cart, ComboItem, Modifier } from './../model/clerkDataContext';
import { ObjectCopier } from './../common/objectCopier';
import { CacheManager } from './../common/cacheManager';
import { Injectable } from '@angular/core';
import { ServiceBase } from "./serviceBase";
import { ClerkDataContext, Inventory, Category, DataContextManager } from "../model/clerkDataContext";
import * as lodash from "lodash";

@Injectable()
export class InventoryService extends ServiceBase {
    constructor(protected http: Http) { super(); }
    async GetInventory(params?: InventoryQueryParams): Promise<Inventory[]> {
        let that = this;
        let result = [];
        let ctx: ClerkDataContext = DataContextManager.Current.ClerkCtx;
        let isCached = CacheManager.Current.isCached("invtList");
        if (params && params.page >= 0 && params.pageCount) {
            let page = params.page - 1;
            let pageCount = params.pageCount;
            //已缓存就从本地缓存中获取商品，不然从indexedDB中获取
            if (isCached) {
                let invtList = CacheManager.Current.get("invtList");
                result = invtList.filter((invt) => {
                    return this.queryInvtFun(invt, params);
                });
                result = result.splice((page * pageCount), pageCount);
            } else {
                result = await ctx.Inventory.Skip(page * pageCount).Take(pageCount)
                    .Where(x => {
                        return that.queryInvtFun(x, params);
                    }).ToList();
            }
        } else {
            if (isCached) {
                let invtList = CacheManager.Current.get("invtList");
                result = invtList.filter((invt) => {
                    return this.queryInvtFun(invt, params);
                });
            } else {
                result = await ctx.Inventory.Where(x => {
                    return that.queryInvtFun(x, params);
                }).ToList();
            }

        }
        if (params && params.code) {
            that.sortInvt(result);
        }
        result = lodash.cloneDeep(result);
        result = result.filter((item) => {
            return item.code != "tablefee";
        })
        return result;
    }

    /**
     * 获得商品分类信息
     */
    GetCategoryList(): Promise<Category[]> {
        let ctx: ClerkDataContext = DataContextManager.Current.ClerkCtx;
        return ctx.Category.Where(x => x.parent == null || x.parent == undefined).ToList();
    }

    /**
     * 通过商品id获取商品
     * @param inventoryId 
     */
    async GetInventoryById(inventoryId: string): Promise<Inventory> {
        if (inventoryId == "0000000000000000000000000000000") {
            return;
        }
        let isCached = CacheManager.Current.isCached("invtList");
        if (isCached) {
            let invtList = CacheManager.Current.get("invtList");
            let result = null;
            if (invtList) {
                result = invtList.find((invt) => {
                    return invt.id == inventoryId;
                });
            }
            if (!result) {
                throw new Error("未找到商品，id:" + inventoryId);
            }
            result = lodash.clone(result);
            return result;
        } else {
            let ctx: ClerkDataContext = DataContextManager.Current.ClerkCtx;
            let result = await ctx.Inventory.First(x => x.id == inventoryId);
            if (!result) {
                throw new Error("未找到商品，id:" + inventoryId);
            }
            return result;
        }

    }

    /**
     * 获得估清的商品
     * @param  {string} inventoryId  商品id
     */
    getSoldOutInvt(inventoryId?: string) {
        // let ctx: ClerkDataContext = DataContextManager.Current.ClerkCtx;
        // return ctx.SoldOut.Where(so => {
        //     if (inventoryId) {
        //         return so.inventoryId == inventoryId && !so.disabled;
        //     } else {
        //         return true;
        //     }
        // }).ToList();
        let url = "api/dataSync/soldoutdInventories/" + this.CurrentStore.id;
        return this.Get(url);
    }

    /**
     * 查询商品的方法
     * @param  {} invt
     * @param  {InventoryQueryParams} params 查询参数（可选）
     * @returns boolean
     */
    queryInvtFun(invt, params?: InventoryQueryParams): boolean {
        let r = false;
        if (params) {
            if (params.code) {
                if (invt.code) {
                    r = (invt.code == params.code);
                }
                if (invt.searchCode && !r) {
                    let searchCodeRangle = invt.searchCode.split("|");
                    for (let i = 0; i < searchCodeRangle.length; i++) {
                        let code = searchCodeRangle[i];
                        r = code.indexOf(params.code) > -1;
                        if (r) {
                            code == params.code ? (invt.fullMatch = true) : delete invt.fullMatch;
                            break;
                        }
                    }
                }
            }
            if (params.categoryId) {
                if (invt.categories instanceof Array) {
                    for (let item of invt.categories) {
                        if (item.id == params.categoryId) {
                            r = true;
                            break;
                        }
                    }
                }
                else {
                    for (let key in <any>invt.categories) {
                        if (invt.categories[key].id == params.categoryId) {
                            r = true;
                            break;
                        }
                    }
                }
            } else if (params.categoryId == "") {
                return r = true;
            }
        }
        else {
            r = true;
        }
        return r;
    }

    /**
     * 对商品进行全匹配查询的排序
     */
    sortInvt(invts) {
        if (!invts || !invts.length) {
            return;
        }
        if (invts.length == 1) {
            delete invts[0].fullMatch;
            return;
        }
        //通过fullMatch标识排序
        invts.sort(a => {
            if (a.fullMatch) {
                return -1;
            }
            return 1;
        });
        //删除fullMatch标识属性
        invts.forEach(i => {
            delete i.fullMatch;
        })
    }

    /**
     * 构建购物车中套餐的信息
     * @param  {Inventory} inventory 套餐中对应的每项商品
     * @param  {} baseItem  商品的基本信息
     * @param  {} qty  该商品数量
     */
    buildCombo(inventory: Inventory, baseItem, option?): ComboItem {
        let combo = new ComboItem();
        combo.inventoryCode = inventory.code;
        combo.inventoryId = inventory.id;
        combo.inventoryName = inventory.name;
        combo.plusPrice = baseItem.plusPrice;
        combo.type = "combo";
        combo.price = inventory.price;
        // combo.discount = inventory.discount;
        // combo.discounts = inventory.discounts;
        if (baseItem.selectQty) {
            if (option) {
                combo.qty = option.qty * baseItem.qty;
            } else {
                combo.qty = baseItem.qty * baseItem.selectQty;
            }
        } else {
            combo.qty = baseItem.qty;
        }
        // combo.status = inventory.status;
        // combo.amount = inventory.amount;
        // combo.actualPrice = inventory.actualPrice;
        // combo.isEntireDiscount = inventory.isEntireDiscount;
        combo.memberPrices = inventory.memberPrices;
        // combo.refundQty = inventory.refundQty;
        combo.inventory = <any>{ unit: inventory.unit };
        combo.extended = { categories: inventory.categories };
        combo.costPrice = inventory.hasOwnProperty('costPrice') ? inventory.costPrice : inventory.price;
        if (option) {
            combo.extended.description = option.description;
            combo.modifiers = option.modifiers;
        } else {
            combo.modifiers = inventory.modifiers;
        }
        return combo;
    }

    /**
 * 判断当前商品是否包含必选的商品选项
 */
    hasRequire(inventory: Inventory, commonMods: Modifier[]) {
        let isRequire = false;
        if (inventory.modifiers && inventory.modifiers.length) {
            for (let mod of inventory.modifiers) {
                if (mod.isRequired) {
                    isRequire = true;
                    break;
                }
            }
        }

        if (!isRequire && Array.isArray(commonMods) && commonMods.length) {
            for (let mod of commonMods) {
                let boo = true;
                if (mod.applyCategories && mod.applyCategories.length) {
                    boo = false;
                    for (let cat of mod.applyCategories) {
                        let r = inventory.categories.filter(ca => { return ca.id == cat.id });
                        if (r && r.length) {
                            boo = true;
                        }
                    }
                }
                if (mod.isRequired && boo) {
                    isRequire = true;
                    break;
                }
            }
        }

        return isRequire;
    }
}

export interface InventoryQueryParams {
    code?: string;
    categoryId?: string;
    page?: number, //查询第几页数据
    pageCount?: number //每页数据条数
}


